// import { loginApi, logout, getInfoApi } from '@/api/system/user'
import { loginApi, getInfoApi } from "@/api/login"
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { Message } from "element-ui";
const state = {
  token: getToken(),
  isSuper: '',
  avatar: '',
  roles: null, // 1
  menus: null,
  routers: null,
  username: '',
  roleName: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_SUPER: (state, isSuper) => {
    state.isSuper = isSuper
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_ROUTERS: (state, routers) => {
    state.routers = routers
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USERNAME: (state, username) => {
    state.username = username
    console.log('存入用户名',state.username);
    localStorage.setItem('username', username);
  },
  SET_ROLEID: (state, roleIds) => {
    state.roles = roleIds[0]
    
  },
  SET_ROLENAME: (state, roleName) => {
    state.roleName = roleName[0]
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginApi(userInfo).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.tokenValue)
        setToken(data.tokenValue)
        Message({
          message: "登录成功",
          type: "success",
          duration: 2 * 1000,
        });
        resolve()
      }).catch(error => {
        Message({
          message: "登录失败！",
          type: "error",
          duration: 2 * 1000,
        });
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    // console.log('执行了 info');
    return new Promise((resolve, reject) => {
      getInfoApi(state.token).then(response => {
        const { data } = response
        // console.log('成功');
        if (!data) {
          reject('获取失败，请重新登录')
        }
        const { isSuper, menus, routers, username, roleNames } = data

        commit('SET_ROLES', isSuper)
        commit('SET_USERNAME', username)
        commit('SET_ROLENAME', roleNames)
        commit('SET_SUPER', isSuper)
        commit('SET_MENUS', menus)
        commit('SET_ROUTERS', routers)
        // commit('SET_ROLES', roleIds[0])
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    removeToken() // must remove  token  first
    resetRouter()
    sessionStorage.clear()
    location.reload()
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

